package com.jinyang.jetpackdemo.activity

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.service.MyService
import com.jinyang.jetpackdemo.service.MyServiceForeground
import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlinx.android.synthetic.main.activity_service_test.*

/**
 * @author 1
 */
class ServiceTestActivity : AppCompatActivity() {
    private val conn: ServiceConnection by lazy {
        object :ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                LjyLogUtil.d("ServiceConnection.onServiceConnected: ComponentName=$name")
                val myBinder:MyService.MyBinder= service as MyService.MyBinder
                myBinder.doSomeWork()
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                LjyLogUtil.d("ServiceConnection.onServiceDisconnected: ComponentName=$name")
            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service_test)
        btn_start_service.setOnClickListener {
            startService(Intent(this@ServiceTestActivity,MyService::class.java).putExtra("key1",123))
        }
        btn_stop_service.setOnClickListener {
            stopService(Intent(this@ServiceTestActivity,MyService::class.java))
        }
        btn_bind_service.setOnClickListener {
            bindService(Intent(this@ServiceTestActivity,MyService::class.java).putExtra("key2",111),conn,BIND_AUTO_CREATE)
        }
        btn_unbind_service.setOnClickListener {
            unbindService(conn)
        }
        btn_start_service_foreground.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(Intent(this@ServiceTestActivity,MyServiceForeground::class.java))
            }
        }
        btn_stop_service_foreground.setOnClickListener {
            stopService(Intent(this@ServiceTestActivity,MyServiceForeground::class.java))
        }
    }
}